package splug.cjk;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import splug.cjk.packet.BBSCarPoolPacket;

public class MyCarPoolTab1Read extends Thread {
	
	private InputStream is;
	private OutputStream os;
	private double latitude;
	private double longitude;
	
	public MyCarPoolTab1Read(InputStream is, OutputStream os) {
		super();
		this.is = is;
		this.os = os;
	}
	
	@Override
	public void run() {
		super.run();
		
		try {
			ObjectInputStream input = new ObjectInputStream(is);
			BBSCarPoolPacket packet = (BBSCarPoolPacket) input.readObject();
			String id = packet.getId();
			
			Class.forName("com.mysql.jdbc.Driver");
			Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/carpool?useUnicode=true&characterEncoding=euckr","root","apmsetup");
			Statement stmt = conn.createStatement();

			String tmp_query1 = "select title, id from  bbscarpooltab1 where id = '" + id + "' order by number desc";
			String tmp_query2 = "select number, start, finish, time, content, date, latitude, longitude from bbscarpooltab1 where id = '" + id + "'order by number desc";

			stmt.execute("SET CHARACTER SET euckr");
			stmt.execute("set names euckr");

			ResultSet rs1 = stmt.executeQuery(tmp_query1);
			
			ArrayList<Content> content = new ArrayList<Content>();
			ArrayList<BBSCarPoolContent> sub_content = new ArrayList<BBSCarPoolContent>();
			

			while(rs1.next()){
				String str1 = rs1.getString("title");
				String str2 = rs1.getString("id");
				Content c = new Content(str1, str2);
				content.add(c);
			}
			
			rs1 = stmt.executeQuery(tmp_query2);
			
			while(rs1.next()){
				int number = rs1.getInt("number");
				String str1 = rs1.getString("content");
				String str2 = rs1.getString("date");
				String str3 = rs1.getString("start");
				String str4 = rs1.getString("finish");
				String str5 = rs1.getString("time");
				latitude = rs1.getDouble("latitude");
				longitude = rs1.getDouble("longitude");
				
				BBSCarPoolContent c = new BBSCarPoolContent(number, str3, str4, str5, str1, str2, latitude, longitude);
				sub_content.add(c);
			}
			
			packet = new BBSCarPoolPacket(content, sub_content, 0, null, null,null,null,null,null,null,latitude,longitude);
			ObjectOutputStream output = new ObjectOutputStream(os);
			output.writeObject(packet);
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
